package cn.caidabao.camunda_demo.listener.execution.start;

import cn.caidabao.camunda_demo.common.CaiCamundaConstant;
import cn.caidabao.camunda_demo.pojo.po.TCaiProcess;
import cn.caidabao.camunda_demo.service.ITCaiProcessService;
import cn.caidabao.camunda_demo.util.CamundaUtil;
import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpmn.instance.Process;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author cjn
 * @since 2024-07-16 11:26
 */
@Component
@AllArgsConstructor
public class ProcessCreateListener implements ExecutionListener {

    private final ITCaiProcessService caiProcessService;
    private final RepositoryService repositoryService;
    private final CamundaUtil camundaUtil;

    @Override
    public void notify(DelegateExecution delegateExecution) throws Exception {
        String processInstanceId = delegateExecution.getProcessInstanceId();
        String processDefinitionId = delegateExecution.getProcessDefinitionId();
        BpmnModelInstance processBpmnModelInstance = repositoryService.getBpmnModelInstance(processDefinitionId);
        Process processModel = processBpmnModelInstance.getModelElementById(repositoryService.getProcessDefinition(processDefinitionId).getKey());
        ExtensionElements extensionElements = processModel.getExtensionElements();
        Map<String, String> extensionProperties = camundaUtil.getExtensionProperties(extensionElements);
        TCaiProcess process = new TCaiProcess();
        process.setCamundaProcessInstanceId(processInstanceId);
        String processType = extensionProperties.get(CaiCamundaConstant.processType);
        if (StringUtils.isBlank(processType)){
            processType = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(delegateExecution.getProcessInstanceId()).singleResult().getName();
        }
        process.setProcessType(processType);
        process.setCaiFormTag(extensionProperties.get(CaiCamundaConstant.processFormTag));
        process.setCaiFormType(Integer.parseInt(extensionProperties.get(CaiCamundaConstant.processFormType)));
        process.setOwnerId("1");
        process.setOwnerType("user");
        process.setContent(JSON.toJSONString(delegateExecution.getVariables()));
        caiProcessService.save(process);
    }
}
